/*
 * Copyright (C) 2011, EADS France
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 */
package xowl.interpreter.impl;

import java.util.List;
import xowl.interpreter.XOWLException;

/**
 *
 * @author Laurent WOUTERS
 */
public class StatementForEachRunner extends StatementRunner {
    private xowl.lang.actions.ForEach statement;
    private xowl.lang.runtime.Array array;
    private List<xowl.lang.runtime.Value> values;
    private int index;
    private boolean isAtLoopEnd;

    public StatementForEachRunner(xowl.lang.actions.ForEach statement, ThreadRunner runner) {
        super(runner);
        this.statement = statement;
        this.array = null;
        this.values = null;
        this.index = 0;
        this.isAtLoopEnd = false;
    }

    @Override public String getFile() { return statement.getFile(); }
    @Override public int getLine() { return statement.getLine(); }
    @Override public void execute() throws XOWLException {
        if (array == null) {
            // First execution
            array = (xowl.lang.runtime.Array)runner.evaluator.evaluate(runner.evaluator, statement.getArray());
            values = xowl.utils.Values.toList(array);
            index = 0;
        }
        
        if (index >= values.size())
        {
            // Finished looping
            if (index != 0)
                runner.contextPop();
            runner.statementPop();
            return;
        }
        
        if (isAtLoopEnd) {
            // Pop iteration specific context
            runner.contextPop();
            isAtLoopEnd = false;
        } else {
            ThreadContext context = runner.contextCreate();
            context.assign(statement.getVariable(), values.get(index));
            runner.statementPush(statement.getContains());
            index++;
            isAtLoopEnd = true;
        }
    }
    @Override public boolean onBreak() {
        // Was in an iteration => pop iteration specific context and FOR context
        runner.contextPop();
        runner.contextPop();
        return false;
    }
}
